package com.shengqi.xinnongren.work.ui.user.activities;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.shengqi.xinnongren.R;
import com.shengqi.xinnongren.common.base.BaseMvpActivity;
import com.shengqi.xinnongren.common.utils.ToastHelper;
import com.shengqi.xinnongren.common.widgets.CustomDialog;
import com.shengqi.xinnongren.work.event.RefreshEvent;
import com.shengqi.xinnongren.work.ui.goods.activities.ChoosePayTypeActivity;
import com.shengqi.xinnongren.work.ui.home.activities.TakeGoodsActivity;
import com.shengqi.xinnongren.work.ui.user.model.OrderDetailsBean;
import com.shengqi.xinnongren.work.ui.user.presenter.OrderDetailsPresenter;
import com.shengqi.xinnongren.work.ui.user.view.OrderDetailsView;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class OrderDetailsActivity extends BaseMvpActivity<OrderDetailsView, OrderDetailsPresenter> implements OrderDetailsView {

    private static final String EXTRA_ORDER_ID = "order_id";

    @BindView(R.id.ll_order_tips)
    LinearLayout mLlOrderTips;

    @BindView(R.id.tv_store_name)
    TextView mTvStoreName;
    @BindView(R.id.tv_store_address)
    TextView mTvStoreAddress;
    @BindView(R.id.tv_store_tel)
    TextView mTvStoreTel;

    @BindView(R.id.tv_take_goods_type)
    TextView mTvTakeGoodsType;
    @BindView(R.id.tv_order_sn)
    TextView mTvOrderSn;
    @BindView(R.id.tv_order_status)
    TextView mTvOrderStatus;

    @BindView(R.id.tv_commit_order_time)
    TextView mTvCommitOrderTime;
    @BindView(R.id.tv_take_goods_date)
    TextView mTvTakeGoodsDate;
    @BindView(R.id.tv_take_goods_time)
    TextView mTvTakeGoodsTime;
    @BindView(R.id.tv_actual_take_goods_time)
    TextView mTvActualTakeGoodsTime;
    @BindView(R.id.tv_use_coupon_money)
    TextView mTvUseCouponMoney;
    @BindView(R.id.tv_use_integral_money)
    TextView mTvUseIntegralMoney;
    @BindView(R.id.tv_pay_type)
    TextView mTvPayType;

    @BindView(R.id.rv_goods)
    RecyclerView mRecyclerView;

    @BindView(R.id.tv_order_total_money)
    TextView mTvOrderTotalMoney;

    //操作
    @BindView(R.id.tv_order_cancel)
    TextView tvOrderCancel;
    @BindView(R.id.tv_order_pay)
    TextView tvOrderPay;
    @BindView(R.id.tv_order_shouhuo)
    TextView tvOrderShouHuo;
    @BindView(R.id.tv_order_quhuo)
    TextView tvOrderQuHuo;
    @BindView(R.id.tv_order_tuikuan)
    TextView tvOrderTuiKuan;
    @BindView(R.id.tv_order_pjdd)
    TextView tvOrderPjdd;
    @BindView(R.id.tv_order_ckpj)
    TextView tvOrderCkpj;
    @BindView(R.id.tv_order_qhcode)
    TextView tvOrderQuCode;
    @BindView(R.id.tv_order_tuihuoinfo)
    TextView tvOrderTuiHuoInfo;

    private String mOrderId;

    List<OrderDetailsBean.ComInfosBean> mList;
    private MyAdapter mAdapter;

    /**
     * @param context
     * @param orderId 订单id
     */
    public static void start(Context context, String orderId) {
        Intent intent = new Intent(context, OrderDetailsActivity.class);
        intent.putExtra(EXTRA_ORDER_ID, orderId);
        context.startActivity(intent);
    }

    @Override
    protected int setContentLayoutRes() {
        return R.layout.activity_order_details;
    }

    @Override
    protected void initView() {
        Intent intent = getIntent();
        if (intent != null) {
            mOrderId = intent.getStringExtra(EXTRA_ORDER_ID);
        }

        mList = new ArrayList<>();
        mAdapter = new MyAdapter();
        mRecyclerView.setAdapter(mAdapter);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        });

    }

    private void initOperation(String operation) {
        if (operation == null)
            return;
        //0取消订单 1确认支付 2确认收货 3确认提货 4申请退款 5评价订单 6查看评价 7取货二维码 8退货详情
        tvOrderCancel.setVisibility(operation.contains("0") ? View.VISIBLE : View.GONE);
        tvOrderPay.setVisibility(operation.contains("1") ? View.VISIBLE : View.GONE);
        tvOrderShouHuo.setVisibility(operation.contains("2") ? View.VISIBLE : View.GONE);
        tvOrderQuHuo.setVisibility(operation.contains("3") ? View.VISIBLE : View.GONE);
        tvOrderTuiKuan.setVisibility(operation.contains("4") ? View.VISIBLE : View.GONE);
        tvOrderPjdd.setVisibility(operation.contains("5") ? View.VISIBLE : View.GONE);
        tvOrderCkpj.setVisibility(operation.contains("6") ? View.VISIBLE : View.GONE);
        tvOrderQuCode.setVisibility(operation.contains("7") ? View.VISIBLE : View.GONE);
        tvOrderTuiHuoInfo.setVisibility(operation.contains("8") ? View.VISIBLE : View.GONE);


        tvOrderCancel.setOnClickListener(v -> mPresenter.cancelOrder(mOrderId));
        tvOrderPay.setOnClickListener(v -> ChoosePayTypeActivity.start(this, mOrderId));
        tvOrderShouHuo.setOnClickListener(v -> confirmDialog(mOrderId));
        tvOrderQuHuo.setOnClickListener(v -> confirmDialog(mOrderId));
        tvOrderTuiKuan.setOnClickListener(v -> ApplyRefundActivity.start(this, mOrderId));
        tvOrderPjdd.setOnClickListener(v -> CommitCommentActivity.start(this, mOrderId));
        tvOrderCkpj.setOnClickListener(v -> startActivity(new Intent(this, MyCommentActivity.class)));
        tvOrderQuCode.setOnClickListener(v -> startActivity(new Intent(this, TakeGoodsActivity.class)));
        tvOrderTuiHuoInfo.setOnClickListener(v -> RefundDetailsActivity.start(this, mOrderId));
    }

    public void confirmDialog(String id) {
        new CustomDialog.Builder(this).setTitle("提示")
                .setContent("是否确认操作")
                .setListener(new CustomDialog.OnButtonClickListener() {
                    @Override
                    public void onConfirm(Dialog dialog) {
                        mPresenter.confirmOrder(id);
                        dialog.dismiss();
                    }

                    @Override
                    public void onCancel(Dialog dialog) {
                        dialog.dismiss();
                    }
                }).build().show();
    }

    @Override
    protected void initData() {

    }

    @Override
    public void onResume() {
        super.onResume();
        mPresenter.getData(mOrderId);
    }

    /**
     * 关闭提示
     */
    @OnClick(R.id.iv_close_tips)
    void iv_close_tips() {
        mLlOrderTips.setVisibility(View.GONE);
    }

    @Override
    protected OrderDetailsPresenter createPresenter() {
        return new OrderDetailsPresenter();
    }

    @Override
    public void showLoadingView() {
        showLoadingDialog();
    }

    @Override
    public void hideLoadingView() {
        hideLoadingDialog();
    }

    @Override
    public void onNetworkError() {
        hideLoadingDialog();
    }

    @Override
    public void showOrderDetails(OrderDetailsBean bean) {

        mTvStoreName.setText(bean.getStoreName());
        mTvStoreAddress.setText(bean.getStoreAddress());
        mTvStoreTel.setText(String.format("联系电话：%s", bean.getStorePhone()));

        mTvTakeGoodsType.setText(bean.getWayMode() == 1 ? "门店自提" : "送货上门");
        mTvTakeGoodsType.setBackgroundResource(bean.getWayMode() == 1 ? R.drawable.bg_order_tag_green : R.drawable.bg_order_tag_yellow);
        mTvOrderSn.setText(bean.getOrderNO());
        mTvOrderStatus.setText(bean.getStatus());

        mTvCommitOrderTime.setText(bean.getOrderTime());
        mTvTakeGoodsDate.setText(bean.getPickDate());
        mTvTakeGoodsTime.setText(bean.getPickTime());
        mTvActualTakeGoodsTime.setText(bean.getTruePickDate());
        mTvUseCouponMoney.setText(bean.getCouponAmount());
        mTvUseIntegralMoney.setText(bean.getIntegralMoney());
        mTvPayType.setText(bean.getPayMent());

        mTvOrderTotalMoney.setText(String.format("订单总额￥%s", bean.getOrderAmount()));

        List<OrderDetailsBean.ComInfosBean> comInfos = bean.getComInfos();
        mList.clear();
        mList.addAll(comInfos);
        mAdapter.notifyDataSetChanged();

        initOperation(bean.getOperation());
    }

    @Override
    public void showRequestFailed(String message) {
        ToastHelper.getInstance(this).showWarn(message);
    }

    @Override
    public void showCancelOrderRes(String message) {
        ToastHelper.getInstance(this).showSucceed(message);
        sendEvent();
    }

    @Override
    public void showConfirmOrderRes(String message) {
        ToastHelper.getInstance(this).showSucceed(message);
        sendEvent();
    }

    /**
     * 通过EventBus发送通知
     */
    private void sendEvent() {
        EventBus.getDefault().post(new RefreshEvent());
        finish();
    }


    class MyAdapter extends RecyclerView.Adapter<MyAdapter.Holder> {
        @NonNull
        @Override
        public Holder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            Holder holder = new Holder(getLayoutInflater().inflate(R.layout.item_test, parent, false));
            return holder;
        }

        @Override
        public void onBindViewHolder(@NonNull Holder holder, int position) {
            OrderDetailsBean.ComInfosBean comInfosBean = mList.get(position);
            holder.tv_name.setText(comInfosBean.getCommodityName());

            holder.rv.setAdapter(new MyAdapter2(comInfosBean.getSkuList()));
            holder.rv.setLayoutManager(new LinearLayoutManager(OrderDetailsActivity.this) {
                @Override
                public boolean canScrollVertically() {
                    return false;
                }
            });

        }

        @Override
        public int getItemCount() {
            return mList.size();
        }

        public class Holder extends RecyclerView.ViewHolder {
            @BindView(R.id.rv_list)
            RecyclerView rv;
            @BindView(R.id.tv_name)
            TextView tv_name;

            public Holder(View itemView) {
                super(itemView);
                ButterKnife.bind(this, itemView);
            }
        }
    }

    class MyAdapter2 extends RecyclerView.Adapter<MyAdapter2.Holder> {
        private List<OrderDetailsBean.ComInfosBean.SkuListBean> mSkuList;

        public MyAdapter2(List<OrderDetailsBean.ComInfosBean.SkuListBean> skuList) {
            mSkuList = skuList;
        }

        @NonNull
        @Override
        public Holder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            return new Holder(getLayoutInflater().inflate(R.layout.item_test2, parent, false));
        }

        @Override
        public void onBindViewHolder(@NonNull Holder holder, int position) {
            OrderDetailsBean.ComInfosBean.SkuListBean bean = mSkuList.get(position);
            holder.item_num.setText(String.format("x%s", bean.getQuantity()));
            holder.item_price.setText(String.format("￥%s", bean.getSkuPriceInfo()));
            holder.item_specification.setText(String.format("%s%s/%s", bean.getComQuantity(), bean.getSkuUnit(), bean.getComUnit()));
            holder.item_unit_price.setText(String.format("每%s￥%s元", bean.getSkuUnit(), bean.getUnitPrice()));
        }

        @Override
        public int getItemCount() {
            return mSkuList.size();
        }

        public class Holder extends RecyclerView.ViewHolder {
            @BindView(R.id.item_num)
            TextView item_num;
            @BindView(R.id.item_price)
            TextView item_price;
            @BindView(R.id.item_specification)
            TextView item_specification;
            @BindView(R.id.item_unit_price)
            TextView item_unit_price;

            public Holder(View itemView) {
                super(itemView);
                ButterKnife.bind(this, itemView);
            }
        }
    }
}
